//
//  ContentViewController.m
//  EasyChat
//
//  Created by dllo on 16/6/13.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "ContentViewController.h"
#import "AddFriendsViewController.h"
#import "ChatViewController.h"
#import "ChatConversationViewController.h"


@interface ContentViewController ()<UITableViewDataSource,UITableViewDelegate,EMChatManagerDelegate>

@property (nonatomic, retain) UITableView *tableView;

@property (nonatomic, retain) NSMutableArray *buddyList;//好友列表

@end

@implementation ContentViewController

-(void)dealloc{

    [super dealloc];
        [[EaseMob sharedInstance].chatManager removeDelegate:self];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //聊天管理器的代理
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    
    /*
     *1.好友列表buddylist需要在自动登陆成功后才有值
     *2.buddylist的数据是从本地获取的
     *3.如果要从服务器获取好友列表[EaseMob sharedInstance].chatManager asyncFetchAllPublicGroupsWithCompletion
     *4.如果当前有添加好友请求 环信sdk内部会往数据库的buddy表添加好友记录
     *5.如果程序删除或者用户第一次登陆 buddylist表是没有记录的 要从服务器获取好友列表记录
     解决方案:1.从服务器获取数据
             2.用户第一次登陆后 自动从服务器获取好友列表
     */
    
    
    self.navigationItem.title = @"好友列表";
    
  //  self.dataArray = [NSMutableArray array];
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.tableView];
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"CELL"];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addButtonClicked)];
     [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    //修改导航栏标题的颜色 和 大小
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:19],
                                                                      
                                                                      NSForegroundColorAttributeName:[UIColor whiteColor]}];
    
#pragma mark - 好友列表buddylist需要在自动登陆成功后才有值
    //获取好友列表数据
 self.buddyList = [NSMutableArray arrayWithArray:[[EaseMob sharedInstance].chatManager buddyList] ];
    
  //  NSLog(@"========%ld",self.buddyList.count);
    
 
#pragma mark - buddylist没有值得情况 1.第一次登陆 2.自动登录未完成
//    if (self.buddyList.count == 0) {//数据库没有好友记录
//        <#statements#>
//    }
//    
    
}
- (void)addButtonClicked
{
    AddFriendsViewController *addFriendsVC = [AddFriendsViewController new];

    [self.navigationController pushViewController:addFriendsVC animated:YES];
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.buddyList.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CELL" forIndexPath:indexPath];
    
  //1.获取"好友"模型
    EMBuddy *buddy = self.buddyList[indexPath.row];
    //2.显示头像和名称
    cell.imageView.image = [UIImage imageNamed:@"chatListCellHead.png"];
    cell.textLabel.text = buddy.username;
    
    
    
    return cell;


}
//点击跳转聊天

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{



    
    self.hidesBottomBarWhenPushed = YES;
    ChatConversationViewController *chatConVC = [ChatConversationViewController new];
    [self.navigationController pushViewController:chatConVC animated:YES];
    self.hidesBottomBarWhenPushed = NO;
    
    //往聊天控制器传递一个buddy值
    //判断跳转进去的控制器是不是聊天控制器
    
    NSLog(@"--------%@",self.buddyList);
    
   // id destVC = segue.destinationViewController;
//    if ([destVC isKindOfClass:[ChatConversationViewController class]]) {
        //获取点中的行
        NSInteger selectedRow = [self.tableView indexPathForSelectedRow].row;
      //  ChatConversationViewController *ChatVC = destVC;
        chatConVC.buddy = self.buddyList[selectedRow];
    
    



}



#pragma mark - chatmanager的代理
-(void)didAutoLoginWithInfo:(NSDictionary *)loginInfo error:(EMError *)error{

    if (!error) {//自动登录成功 此时buddylist有值了
        
        self.buddyList = [[EaseMob sharedInstance].chatManager buddyList];
        NSLog(@"===%@",self.buddyList);
        [self.tableView reloadData];
    }


}

#pragma mark - 好友添加请求同意
-(void)didAcceptedByBuddy:(NSString *)username{

//把好友加到表格里
  NSArray *buddyList = [[EaseMob sharedInstance].chatManager buddyList];
    NSLog(@"好友添加请求同意 %@",buddyList);
    
    //此时好友个数仍然是未添加时候的,重新从服务器获取
    [self loadBuddyListFromServer];

}

//从服务器获取好友列表
-(void)loadBuddyListFromServer{

  [[EaseMob sharedInstance].chatManager asyncFetchBuddyListWithCompletion:^(NSArray *buddyList, EMError *error) {
      
      self.buddyList = buddyList;
      [self.tableView reloadData];
      
  } onQueue:nil];
    
    
}

#pragma mark - 好友数据列表被更新
-(void)didUpdateBuddyList:(NSArray *)buddyList changedBuddies:(NSArray *)changedBuddies isAdd:(BOOL)isAdd{

    NSLog(@"好友数据列表被更新 %@",buddyList);
    //重新赋值数据源
    self.buddyList = buddyList;
    [self.tableView reloadData];


}

//实现表格的delete
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        //获取移除好友的名字
        EMBuddy *buddy = self.buddyList[indexPath.row];
        NSString *deleteUserName = buddy.username;
        
        //删除好友
        [[EaseMob sharedInstance].chatManager removeBuddy:deleteUserName removeFromRemote:YES error:nil];
    }



}

//-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
//
////往聊天控制器传递一个buddy值
//    //判断跳转进去的控制器是不是聊天控制器
//    
//    NSLog(@"+++++++%@",self.buddyList);
//    
//    id destVC = segue.destinationViewController;
//    if ([destVC isKindOfClass:[ChatConversationViewController class]]) {
//        //获取点中的行
//        NSInteger selectedRow = [self.tableView indexPathForSelectedRow].row;
//        ChatConversationViewController *ChatVC = destVC;
//        ChatVC.buddy = self.buddyList[selectedRow];
//    }
//
//
//}

#pragma mark - 被好友删除了
-(void)didRemovedByBuddy:(NSString *)username{

    //刷新表格
    [self loadBuddyListFromServer];



}


@end
